<?php
/**
 * ECSHOP 批量添加会员、订单、评论
 * 网站地址: http://www.ec100.com；
 * $Author: rubing.zhao $
 * $Id: batch.php 20150319 $
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require('includes/lib_goods.php');

/*------------------------------------------------------ */
//-- 1.批量添加会员
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add_users')
{
    /* 检查权限 */
    admin_priv('batch');

    /* 参数赋值 */
    $ur_here = $_LANG['01_batch_add_users'];
    $smarty->assign('ur_here', $ur_here);

    /* 显示模板 */
    assign_query_info();
    $smarty->display('batch_add_users.htm');
}

/*------------------------------------------------------ */
//-- 1.批量添加会员：处理
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'users_upload')
{
    /* 检查权限 */
    admin_priv('batch');

    $password = empty($_POST['password']) ? '' : trim($_POST['password']);
    $again_password = empty($_POST['again_password']) ? '' : trim($_POST['again_password']);
    $this_password = compile_password(array('password'=>$password));

    if($password != $again_password){
        $msg = $_LANG['again_pwd_different'];
        sys_msg($msg, 1);
    }

    if (@is_uploaded_file($_FILES['users_file']['tmp_name'])){
        $f = $_FILES["users_file"];
        $name = $f['name'];
        $type = $f['type'];
        $error = $f['error'];
        $tmp = $f['tmp_name'];
        $size = $f['size'];

        if($error==0){
            move_uploaded_file($tmp,"./$name");
            $read_file = read_user($name);

            foreach($read_file as $v){
                /* 检查user_name是否重复 */
                $sql = "SELECT count(*)  FROM " . $ecs->table('users').
                    " WHERE user_name = '" . $v . "'";
                $is_insert = $db->getOne($sql);
                if(!$is_insert){
                    $sql = "INSERT INTO " . $ecs->table('users') . " (user_name, password) values('$v', '$this_password')";
                    $db->query($sql);
                }
            }
        }
    }
    unlink("./".$name);
    /* 参数赋值 */
    $smarty->assign('ur_here', $_LANG["do_batch_add_orders"]);

    /* 显示模板 */
    assign_query_info();
    /* 显示提示信息，返回商品列表 */
    $link[] = array('href' => 'index.php?act=main', 'text' => $_LANG['back_index_html']);
    sys_msg($_LANG['batch_upload_ok'], 0, $link);
}


/*------------------------------------------------------ */
//-- 2.批量添加订单
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_orders')
{
    /* 检查权限 */
    admin_priv('batch');

    /* 参数赋值 */
    $ur_here = $_LANG['02_batch_add_orders'];
    $smarty->assign('ur_here', $ur_here);

    /* 显示模板 */
    assign_query_info();
    $smarty->display('batch_add_orders.htm');
}

/*------------------------------------------------------ */
//-- 2.批量添加订单：处理
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'orders_upload')
{
    /* 检查权限 */
    admin_priv('batch');

    $goods_id_arr = empty($_POST['goods_id_arr']) ? '' : trim($_POST['goods_id_arr']);
    $buy_num = empty($_POST['buy_num']) ? 1 : $_POST['buy_num'];

    $goods_ids = array();
    $goods_ids = explode(",",trim($goods_id_arr));

    if (@is_uploaded_file($_FILES['users_file']['tmp_name'])){
        $f = $_FILES["users_file"];
        $name = $f['name'];
        $type = $f['type'];
        $error = $f['error'];
        $tmp = $f['tmp_name'];
        $size = $f['size'];

        if($error==0){
            move_uploaded_file($tmp,"./$name");
            $read_file = read_user($name);

            foreach($goods_ids as $vo){
                $attrs = array();
                $sql = "SELECT ga.attr_id, ga.goods_attr_id, ga.attr_value, ga.attr_price, a.attr_name FROM " . 
                       $ecs->table('goods_attr') . " AS ga " .
                       " LEFT JOIN " . $ecs->table('attribute') . " AS a " .
                       " ON ga.attr_id = a.attr_id WHERE ga.goods_id = $vo AND a.attr_type = 1";
                $attrs = $db->getAll($sql);
                $u=array();
                foreach($attrs as $k=>&$e){
                    $attr=&$e['attr_id'];
                    if(!isset($u[$attr])){
                        $u[$attr]=$e;
                        unset($u[$attr]['goods_attr_id'],$u[$attr]['attr_value'],$u[$attr]['attr_price']);
                    }
                    $u[$attr]['goods'][]=array('goods_attr_id'=>$e['goods_attr_id'],'attr_value'=>$e['attr_value'],'attr_price'=>$e['attr_price']);
                }
                $attrs=array_values($u); unset($u);
                $last_attrs = array();
                $len = count($attrs);
                if ($len > 0) 
                {
                    if($len == 1)
                    {
                        $temp_index = 0;
                        foreach ($attrs[0]['goods'] as $k0 => $v0) 
                        {
                            if ($v0['attr_price']) 
                            {
                                $v0_p = '[' . $v0['attr_price'] . ']';
                            }
                            else
                            {
                                $v0_p = '';
                            }
                            $last_attrs[$temp_index]['goods_attr'] = $attrs[0]['attr_name'] . ':' . $v0['attr_value'] . $v0_p;
                            $last_attrs[$temp_index]['goods_price'] = $v0['attr_price'];
                            $temp_index ++;
                        }
                    }
                    else
                    {
                        $temp_index = 0;
                        foreach ($attrs[0]['goods'] as $k0 => $v0) 
                        {
                            foreach ($attrs[1]['goods'] as $k1 => $v1) 
                            {
                                if ($v0['attr_price']) 
                                {
                                    $v0_p = '[' . $v0['attr_price'] . ']';
                                }
                                else
                                {
                                    $v0_p = '';
                                }
                                if ($v1['attr_price']) 
                                {
                                    $v1_p = '[' . $v1['attr_price'] . ']';
                                }
                                else
                                {
                                    $v1_p = '';
                                }
                                $last_attrs[$temp_index]['goods_attr'] = $attrs[0]['attr_name'] . ':' . $v0['attr_value'] . $v0_p . ' ' . $attrs[1]['attr_name'] . ':' . $v1['attr_value'] . $v1_p;
                                $last_attrs[$temp_index]['goods_price'] = $v0['attr_price'] + $v1['attr_price'];
                                $temp_index ++;
                            }
                        }
                    }
                }
                
                foreach($read_file as $v)
                {
                    $goods_info = array();
                    $sql = "SELECT * FROM " . $ecs->table('goods') . " WHERE goods_id = " . $vo;
                    $goods_info = $db->getRow($sql);
                    if($goods_info){
                        /* 获取用户ID */
                        $sql = "SELECT *  FROM " . $ecs->table('users').
                            " WHERE user_name = '" . $v . "'";
                        $user_info = $db->getRow($sql);

                        if($user_info){
                            $order_sn = get_order_sn(); //获取新订单号
                            $goods_number = rand(1,$buy_num);

                            $goods_name = $goods_info['goods_name'];
                            $goods_sn = $goods_info['goods_sn'];
                            $market_price = $goods_info['market_price'];
                            $goods_price = $goods_info['shop_price'];
                            $order_amount = 0;
                            $add_time = time()+rand(10000,30000);
                            $pay_time = time()+rand(80000,240000);

                            $lenth = count($last_attrs);
                            if ($lenth > 0)
                            {
                                $n_key = rand(0,$lenth-1);
                                $goods_attr = $last_attrs[$n_key]['goods_attr'];
                                $goods_info['shop_price'] = $goods_info['shop_price'] + $last_attrs[$n_key]['goods_price']; 
                                $market_price = $market_price + $last_attrs[$n_key]['goods_price'];
                                $goods_price = $goods_price + $last_attrs[$n_key]['goods_price'];
                            }
                            else
                            {
                                $goods_attr = '';
                            }

                            $goods_amount = $goods_info['shop_price'] * $goods_number;
                            $user_id = $user_info['user_id'];
                            $consignee = $user_info['user_name'];
                        
                            $sql = "INSERT INTO " . $ecs->table('order_info') . " (order_sn, user_id, consignee, country, province, city, district, address, shipping_id, pay_id, goods_amount, shipping_fee, order_amount, add_time, order_status, shipping_status, pay_status, pay_time, is_false) values('$order_sn', '$user_id', '$consignee', 1, 2, 52, 502, '收货地址', 3, 3, '$goods_amount', 0, '$order_amount', '$add_time',1,2,2,'$pay_time',1)";
                            $db->query($sql);
                            $new_order_id = $db->insert_id();

                            $sql = "INSERT INTO " . $ecs->table('order_goods') . " (order_id, goods_id, goods_name, goods_sn, goods_number, market_price, goods_price, goods_attr, is_real) values('$new_order_id', '$vo', '$goods_name', '$goods_sn', '$goods_number', '$market_price', '$goods_price', '$goods_attr', 1)";
                            $db->query($sql);
                        }
                    }
                }
            }

        }
        else{
            unlink("./".$name);
            $link[] = array('href' => 'index.php?act=main', 'text' => $_LANG['back_index_html']);
            sys_msg($_LANG['users_file_error'], 1, $link);
        }
    }
    unlink("./".$name);
    /* 参数赋值 */
    $smarty->assign('ur_here', $_LANG['do_batch_add_orders']);

    /* 显示模板 */
    assign_query_info();
    /* 显示提示信息，返回商品列表 */
    $link[] = array('href' => 'index.php?act=main', 'text' => $_LANG['back_index_html']);
    sys_msg($_LANG['batch_upload_ok'], 0, $link);
}


/*------------------------------------------------------ */
//-- 3.批量添加评论
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_comments')
{
    /* 检查权限 */
    admin_priv('batch');

    /* 参数赋值 */
    $ur_here = $_LANG['03_batch_add_comments'];
    $smarty->assign('ur_here', $ur_here);

    /* 显示模板 */
    assign_query_info();
    $smarty->display('batch_add_comments.htm');
}

/*------------------------------------------------------ */
//-- 2.批量添加订单：处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'comments_upload')
{
    /* 检查权限 */
    admin_priv('batch');

    $goods_id_arr = empty($_POST['goods_id_arr']) ? '' : trim($_POST['goods_id_arr']);
    $comment_num = empty($_POST['comment_num']) ? 1 : $_POST['comment_num'];

    $goods_ids = array();
    $goods_ids = explode(",",trim($goods_id_arr));

    if (@is_uploaded_file($_FILES['users_file']['tmp_name'])) {
        $f = $_FILES["users_file"];
        $name = $f['name'];
        $type = $f['type'];
        $error = $f['error'];
        $tmp = $f['tmp_name'];
        $size = $f['size'];

        if ($error == 0) {
            move_uploaded_file($tmp, "./$name");
            $read_file = read_user($name);
        }else{
            unlink("./".$name);
            $link[] = array('href' => 'index.php?act=main', 'text' => $_LANG['back_index_html']);
            sys_msg($_LANG['users_file_error'], 1, $link);
        }
    }

    if (@is_uploaded_file($_FILES['comments_file']['tmp_name'])) {
        $f = $_FILES["comments_file"];
        $name = $f['name'];
        $type = $f['type'];
        $error = $f['error'];
        $tmp = $f['tmp_name'];
        $size = $f['size'];

        if ($error == 0) {
            move_uploaded_file($tmp, "./$name");
            $read_comment = read_comment($name);
        }else{
            unlink("./".$name);
            $link[] = array('href' => 'index.php?act=main', 'text' => $_LANG['back_index_html']);
            sys_msg($_LANG['users_file_error'], 1, $link);
        }
    }

    $user_count = count($read_file);
    $comment_count = count($read_comment);
    for ($i=0;$i<$comment_num;$i++)
    {
        foreach ($goods_ids as $vo)
        {
            $this_user = $read_file[rand(0,$user_count-1)];
            $sql = "SELECT *  FROM " . $ecs->table('users').
                " WHERE user_name = '" . $this_user . "'";
            $user_info = $db->getRow($sql);
            $email = $user_info['email'];
            $user_name = $user_info['user_name'];
            $user_id = $user_info['user_id'];
            $this_time = gmtime()+rand(37700,377000);

            $this_comment = $read_comment[rand(0,$comment_count-1)];
            $this_rank = rand(3,5);
            $sql = "INSERT INTO " . $ecs->table('comment') . " (id_value, email, user_name, content, comment_rank, add_time, status,user_id) values('$vo', '$email', '$user_name', '$this_comment', '$this_rank', '$this_time', 1, '$user_id')";
            $db->query($sql);
        }
    }
    //留言文件处理后的数组  $read_comment
    //用户文件处理后的数组  $read_file
    unlink("./".$name);
    /* 参数赋值 */
    $smarty->assign('ur_here', $_LANG['do_batch_add_comment']);

    /* 显示模板 */
    assign_query_info();
    /* 显示提示信息，返回商品列表 */
    $link[] = array('href' => 'index.php?act=main', 'text' => $_LANG['back_index_html']);
    sys_msg($_LANG['batch_upload_ok'], 0, $link);
}

//read_user
function read_user($files){
    if (file_exists($files)){
        $file = file_get_contents($files);
        $file = explode(",",trim($file));
        return $file;
    } else {
        echo "The file named ".$files['name']."can not find.";
    }
}
//read_user end

//read_comment
function read_comment($files){
    if (file_exists($files)){
        $file = file_get_contents($files);
        $file = explode('$_ec100_$',trim($file));
        return $file;
    } else {
        echo "The file named ".$files['name']."can not find.";
    }
}
//read_comment end


/**
 *  编译密码函数
 *
 * @access  public
 * @param   array   $cfg 包含参数为 $password, $md5password, $salt, $type
 *
 * @return void
 */
function compile_password ($cfg)
{
    if (isset($cfg['password']))
    {
        $cfg['md5password'] = md5($cfg['password']);
    }
    if (empty($cfg['type']))
    {
        $cfg['type'] = PWD_MD5;
    }

    switch ($cfg['type'])
    {
        case PWD_MD5 :
            if(!empty($cfg['ec_salt']))
            {
                return md5($cfg['md5password'].$cfg['ec_salt']);
            }
            else
            {
                return $cfg['md5password'];
            }

        case PWD_PRE_SALT :
            if (empty($cfg['salt']))
            {
                $cfg['salt'] = '';
            }

            return md5($cfg['salt'] . $cfg['md5password']);

        case PWD_SUF_SALT :
            if (empty($cfg['salt']))
            {
                $cfg['salt'] = '';
            }

            return md5($cfg['md5password'] . $cfg['salt']);

        default:
            return '';
    }
}

/**
 * 得到新订单号
 * @return  string
 */
function get_order_sn()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);

    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}
?>